﻿#region
/*******************************************************************************
** File Name:		    DepartmentService.cs
** Creator:		        chao.jiang 
** EMail:               chao.jiang 
** Create date:	        
** Latest Modifier:
** Latest Modify date:
** Description:		    
** Modify History:
**
** Code Review:
**
** Version number:       1.0.0
*********************************************************************************/
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Phoenix.Service.Contracts;
using Phoenix.Service.Model;
using Phoenix.IBatisRepository;
using Phoenix.Respository;
using System.Data;
using Phoenix.Entity;

namespace Phoenix.Service
{
    public class DepartmentService : IDepartmentService
    {
		 IDepartment department = new DepartmentRepository();
        AdminUserService IAdminUser = new AdminUserService();
		 
		 #region  Auto Generation
		 
        public System.Int32 AddDepartment(DepartmentModel model)
        {
			EDepartment entity = ConvertModelToEntity(model);
			
            return department.AddDepartment(entity);
        }

		public void UpdateByDepartmentID (DepartmentModel model)
		{
			EDepartment entity = ConvertModelToEntity(model);

            department.UpdateByDepartmentID(entity);

		}

		public void DeleteByDepartmentID (System.Int32 departmentID)
		{
		
            department.DeleteByDepartmentID(departmentID);

		}
		 
        public DepartmentModel GetByDepartmentID (System.Int32 departmentID)
        {
        
			EDepartment entity = department.GetByDepartmentID(departmentID);
			
            DepartmentModel model = ConvertEntityToModel(entity);


            return model;
        }
        
	
		public IList<DepartmentModel> GetAll ()
		{
			IList<EDepartment> entity = department.GetAll();
			
			if (entity == null)
            {
                return null;
            }
            
            IList<DepartmentModel> list = new List<DepartmentModel>();

            foreach (var item in entity)
            {
                DepartmentModel model = ConvertEntityToModel(item);
                list.Add(model);
            }
            return list;   
			
		}
		
		private DepartmentModel ConvertEntityToModel(EDepartment entity)
		{
			if (entity == null)
            {
                return null;
            }
			DepartmentModel model = new DepartmentModel();
                        model.DepartmentID = entity.DepartmentID;
                        model.Name = entity.Name;
                        model.ParentID = entity.ParentID;
                        model.Level = entity.Level;
                        model.SortOrder = entity.SortOrder;
                        model.CreateTime = entity.CreateTime;
                        model.IsClosed = entity.IsClosed;
                        return model;
		}
		
		private EDepartment ConvertModelToEntity(DepartmentModel model)
		{
			if (model == null)
            {
                return null;
            }
			EDepartment entity = new EDepartment();
                        entity.DepartmentID = model.DepartmentID;
                        entity.Name = model.Name;
                        entity.ParentID = model.ParentID;
                        entity.Level = model.Level;
                        entity.SortOrder = model.SortOrder;
                        entity.CreateTime = model.CreateTime;
                        entity.IsClosed = model.IsClosed;
                        return entity;
		}
		
		
		
		#endregion

		/// <summary>
		/// 获取部门的Level
		/// </summary>
		/// <param name="departmentID">部门ID</param>
		/// <param name="parentDepartmentID">父部门ID</param>
		/// <returns>level</returns>
		private string GetDepartmentLevel(int departmentID, int parentDepartmentID)
		{
			var departments = GetAll();
			var oldDepartment = departments.Where(p => p.DepartmentID == departmentID).FirstOrDefault();
			if (oldDepartment != null && oldDepartment.ParentID == parentDepartmentID && oldDepartment.Level.Trim() != "")
				return oldDepartment.Level;
			string level = "";
			var childDepartments = departments.Where(p => p.ParentID == parentDepartmentID);
			int maxChildDepartmentLvel = 0;
			foreach (var department in childDepartments)
			{
				string departmentLevel = department.Level.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
				if (departmentLevel != null)
				{
					int childLevel = Convert.ToInt32(departmentLevel);
					maxChildDepartmentLvel = Math.Max(maxChildDepartmentLvel, childLevel);
				}
			}
			var parentDepartment = departments.Where(p => p.DepartmentID == parentDepartmentID).FirstOrDefault();
			if (parentDepartment != null)
			{
				level = parentDepartment.Level;
				level += "-" + (maxChildDepartmentLvel + 1).ToString();
			}
			return level;
		}

		/// <summary>
		/// 获取旧部门级别
		/// </summary>
		/// <param name="departmentID">部门ID</param>
		/// <returns></returns>
		private string GetOldDepartmentLevel(int departmentID)
		{
			var departments = GetAll();
			var oldDepartment = departments.Where(p => p.DepartmentID == departmentID).FirstOrDefault();

			if (oldDepartment != null)
				return oldDepartment.Level;
			return string.Empty;

		}


		/// <summary>
		/// 按级别获取子部门列表
		/// </summary>
		/// <param name="level">级别</param>
		/// <returns></returns>
		private List<DepartmentModel> GetChildDepartments(string level)
		{
			var departments = GetAll();
			return departments.Where(p => ("," + p.Level).Contains("," + level) && p.Level != level).Select(x =>
			{
				return (x);
			}).ToList();
		}

        // 取部门名称
        public string GetDepartmentName(string departmentIDs)
        {
            var departments = GetAll();

            if (string.IsNullOrEmpty(departmentIDs) || departments == null) { return ""; }

            // 分割字符串
            string[] array = departmentIDs.Split(',');
            
            // 取所有与array里的departmentID对应的Department对象,然后取对象的Name属性存在数组里
            string[] names = departments.Where(p => array.Contains(p.DepartmentID.ToString())).Select(x => x.Name).ToArray();

            return string.Join(",", names); // 保存部门名称
        }



		public void Update(DepartmentModel model)
		{
			model.Level = GetDepartmentLevel(model.DepartmentID, model.ParentID);
			EDepartment eDepartment =ConvertModelToEntity(model);
			string oldDepartmentLevel = GetOldDepartmentLevel(model.DepartmentID);
			try
			{
				
					if (model.Level == oldDepartmentLevel)
					{
						//如果级别不变就只更新当前部门信息
						UpdateByDepartmentID(model);
					}
					else
					{
						//级别改变同步子部门级别以及下属帐号级别
						var childDepartments = GetChildDepartments(oldDepartmentLevel);
						department.BatchUpdate(oldDepartmentLevel, model.Level, eDepartment);
						IAdminUser.BatchUpdateByDepartLevel(model.Level, oldDepartmentLevel);
					}
			}
			catch
			{
				//throw new CustomException("修改失败，请稍候重试!");
			}

		}
    }
}